﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using XSTDZ.ERP.Application.DataContracts;
using XSTDZ.ERP.Application;
using XSTDZ.ERP.Infrastructure;
using XSTDZ.ERP.WebApp.Models;
using XSTDZ.ERP.Core.Extentions;
using XSTDZ.ERP.Infrastructure.Authentication;
using XSTDZ.ERP.WebApp.Models.Ado;

namespace XSTDZ.ERP.WebApp.Controllers
{
    //入库订单
    public class ProductInController : Controller
    {
        private readonly IProductInService productInBillServiceImpl = ServiceLocator.Instance.GetService<IProductInService>();	
        //
        // GET: /ProductIn/
        #region 首页
        #region 成都首页
        public ActionResult Index()
        {
            ViewBag.orgCode = SystemConfig.ChengDuCode;
            return View();
        }
        #endregion
        #endregion
        #region 查看详细
        [NoAuthorizated("Detail")]
        public ActionResult Detail(Guid id)
        {
            var billModel = productInBillServiceImpl.GetProductInBill(id);
            return View(billModel);
        }
        #endregion
        #region 保存和提交统一入口
        [NoAuthorizated("AddAndConfirm")]
        [HttpPost]
        public ActionResult AddAndConfirm(ProductInBillDto roductInBillDto)
        {
            bool isConfirm = Convert.ToBoolean(Request["isConfirm"]);
            //订单已确认
            if (roductInBillDto.BillState > 0)
            {
                return new EmptyResult();
            }
            //保存(或更新)
            var aa = Add(roductInBillDto) as ContentResult;
            string actionResult = aa.Content.ToString();
            Guid tempId = Guid.Empty;
            if (Guid.TryParse(actionResult.ToString(), out tempId))
            {
                roductInBillDto.ID = tempId;
            }
            else
            {
                return Content(actionResult.ToString());
            }
            //提交
            if (isConfirm)
            {
              
                if (roductInBillDto.ID != null && !roductInBillDto.ID.Equals(Guid.Empty))//记录已存在
                {
                        Confirm(roductInBillDto.ID);//提交
                }
            }
            return Content("9");
        }
        #endregion
        #region 添加入库单
        #region 成都业务
        [NoAuthorizated("Add")]
        public ActionResult Add(string orgCode, Guid? id)
            {
                ViewBag.orgCode = orgCode;
                return View(AddGet(orgCode,id));
            }
        [HttpPost]
        [NoAuthorizated("Add")]
        public ActionResult Add(ProductInBillDto roductInBillDto)
        {
            if (roductInBillDto.BillState != 1)
            {
                return Content(AddPost(roductInBillDto));
            }
            return Content("0");
        }
        #endregion
       
        #region 通用入库业务操作
        private ProductInBillDto AddGet(string orgCode, Guid? id)
            {
                ProductInBillDto billModel = null;
                if (id == null || !id.HasValue)
                {
                    var NO = new BusinessBillNoCreator().CreateInNextNO();

                    var initSysData = DataInit.GetOrgAndDefaultWareHourse(orgCode);//初始化默认组织机构和仓库
                    var wareHouse = initSysData.Values.FirstOrDefault();
                    var org = initSysData.Keys.FirstOrDefault();
                    //
                    billModel = new ProductInBillDto
                    {
                        ProductInBillNo = NO,
                        StorehouseName = wareHouse.StorehouseName,
                        StorehouseID = wareHouse.Id,
                         SourceOrgName=org.Name,
                          SourceOrgID=org.Id
                    };
                    //初始化默认源组织机构
                    #region 初始化默认源组织机构
                    if (orgCode.ToUpper() == SystemConfig.ShengZhenCode.ToUpper())
                    {
                        var initOrginData = DataInit.GetOrgAndDefaultWareHourse(SystemConfig.ShengZhenCode);
                        var orginOrg = initOrginData.Keys.FirstOrDefault();

                        billModel.SourceOrgID = orginOrg.Id;
                        billModel.SourceOrgName = orginOrg.Name;
                    }
                    #endregion

                    ViewBag.BillId = "";
                }
                else
                {
                    Guid billId;
                    Guid.TryParse(id.ToString(), out billId);
                    billModel = productInBillServiceImpl.GetProductInBill(billId);
                    ViewBag.BillId = billId.ToString();
                }
                ViewBag.TempId = Guid.NewGuid();

                billModel.ProductInDate = DateTime.Today;
                return billModel;
            }
        private string AddPost(ProductInBillDto roductInBillDto)
            {
                #region 弹出框数据获取
                var model = new ProductInBill();
                //仓库ID
                var whId = model.GetRequestFormValues(this.HttpContext, "StorehouseName_val");
                if (!Guid.Empty.Equals(whId))
                {
                    roductInBillDto.StorehouseID = whId;
                }
                //送货人ID
                //var sendid = model.GetRequestFormValues(this.HttpContext, "SenderName_val");
                //if (!Guid.Empty.Equals(sendid))
                //{
                //    roductInBillDto.SenderID = sendid;
                //}
                //员工ID
                var uid = model.GetRequestFormValues(this.HttpContext, "EmployeeName_val");
                if (!Guid.Empty.Equals(uid))
                {
                    roductInBillDto.EmployeeID = uid;
                }
                //组织机构ID
                var sorgid = model.GetRequestFormValues(this.HttpContext, "SourceOrgID");
                if (!Guid.Empty.Equals(sorgid))
                {
                    roductInBillDto.SourceOrgID = sorgid;
                }

                #endregion
                #region 主数据行处理
                roductInBillDto.CreateID = UserModel.GetLoginUserId(this.HttpContext);
                roductInBillDto.SenderID = roductInBillDto.CreateID;
                #endregion
                #region 明细行数据处理

                var result = Request.Form["hidProductBillItems"];
                var detailItems = model.GetProductItems(result);
                if (!string.IsNullOrEmpty(result) && detailItems == null)
                {
                    return "-1";//明细行异常
                }
                detailItems.Each(item => { item.ProductInBillID = roductInBillDto.ID; if (item.ID == item.ProductInBillID && item.ProductInBillID != roductInBillDto.ID && item.ID != null && !item.ID.Equals(Guid.Empty)) { item.ID = Guid.Empty; } });
                #endregion

                #region 数据验证
                if (detailItems == null || detailItems.Count <= 0)
                {
                    ModelState.AddModelError("", "必须至少存在一个明细行！");
                    return "-1";
                }
                #endregion
                if (ModelState.IsValid)
                {
                    try
                    {
                       var id= productInBillServiceImpl.AddProductInBill(roductInBillDto, detailItems);//若存在即更新
                       return id.ToString();
                    }
                    catch (Exception ex)
                    {
                        return "-2";
                    }
                    return "9";
                }
                return "0";
            }
        #endregion
        #endregion
        #region 提交（生成库存）
         //导入确认收货
        [HttpGet]
        [NoAuthorizated("Confirm")]
        public ActionResult Confirm(Guid billId)
        {
            try
            {
                productInBillServiceImpl.ConfirmUpdateStock(billId);
            }
            catch (Exception)
            {
                return Content("0");
            }
            return Content("9");
        }
        #endregion
        #region 删除订单明细（假删除）
        [NoAuthorizated("Delete")]
        public ActionResult Delete(Guid billId,string ids)
        {
            if (ids!="all"&&ids.Trim().Length > 0)
            {
                string[] arrayIds = ids.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                var guidIds = new List<Guid>();
                arrayIds.Each(id => guidIds.Add(Guid.Parse(id)));
                productInBillServiceImpl.ConvertProductInBillDeleteState(billId, guidIds);
                return Content("9");
            }
            else
            {
                productInBillServiceImpl.ConvertProductInBillDeleteState(billId);
                return Content("9");
            }
            return Content("0");
        }
        #endregion
        #region 获取入库单列表数据
        //暂时获取所有数据
        [NoAuthorizated("GetJsonOfProductInBills")]
        public ActionResult GetJsonOfProductInBills(string orgCode)
        {
            #region EF的查询，效率低下，故暂时放弃不用
            /*
            int recordCount = 0;
            var productBills = productInBillServiceImpl.GetProductInBills(out recordCount,1, 100, orgCode.Trim());
            if (productBills != null && productBills .Count() != 0)
            {
                var jsonResult = productBills.Select(u => { u.DeleteState = u.Deleted == 0 ? "正常" : "已删除";
                u.SettleState = u.IsSettle > 0 ? "已结算" : "未结算";
                         return u; 
                });
                var target = Newtonsoft.Json.JsonConvert.SerializeObject(jsonResult);
                target = "{\"Rows\":" + target + ",\"Total\":\"" + recordCount + "\"}";
                return Content(target);
            }
            return Content("");
            */
            #endregion
            return Content(new BLLQuery().GetProductInBills(this.HttpContext));

        }
        /// <summary>
        /// 根据入库单ID，获得入库单所有明细（不包括删除行）
        /// </summary>
        /// <param name="billId"></param>
        /// <returns></returns>
        [NoAuthorizated("GetJsonOfProductInBillDetails")]
        public ActionResult GetJsonOfProductInBillDetails(Guid billId)
        {
            #region EF的查询，效率低下，故暂时放弃不用
            //var productInBillDetails = productInBillServiceImpl.GetProductInBillDetails(billId).Where(p => p.Deleted == 0).ToList();
            //if (productInBillDetails != null && productInBillDetails.Count() != 0)
            //{
            //    var jsonResult = productInBillDetails;
            //    var target = Newtonsoft.Json.JsonConvert.SerializeObject(jsonResult);
            //    target = "{\"Rows\":" + target + ",\"Total\":\"10\"}";
            //    return Content(target);
            //}
            // return Content("");
            #endregion
             if (!billId.Equals(Guid.Empty))
             {
                 return Content(new BLLQuery().GetProductInDetails(billId));
             }
             else
             {
                 return Content("");
             }
        }
        #endregion
        #region 获取入库单明细
         [NoAuthorizated("AddItem")]
        public ActionResult AddItem()
        {
            return View();
        }
        [HttpPost]
        [NoAuthorizated("AddItem")]
        public ActionResult AddItem(ProductInBillDetailDto detailItem)
        {
            if (ModelState.IsValid)
            { 

            }
            return View();
        } 


        #endregion
        #region 深圳首页
        public ActionResult SZIndex()
        {
            ViewBag.orgCode = SystemConfig.ShengZhenCode;
            return View("Index");
        }
        #endregion
    }
}
